<?php
/**
 * Object Relational Persistence Mapping Class for table: rad_result_image
 *
 * @package	com.athena
 * @author	LHV
 */
class RadResultImage extends ORDataObject {

	/**#@+
	 * Fields of table: rad_result_image mapped to class members
	 */
	var $rad_result_image_id    = '';
	var $rad_item_id       		= '';
	var $created           		= '';
	var $full_url          		= '';
	var $thumnail_url      		= '';
    private $logger;

    /* modules/dept_rad/ */
    var $_module_dir            =   '';
    /* rad_images */
    var $_image_folder          =   'rad_images/';
    var $_thumnail_folder       =   'thumbnail/';
    var $_full_folder           =   'full/';
    /* modules/dept_rad/rad_images */
    var $_image_base_dir        =   '';
    var $_type_folders          =   array();
	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'rad_result_image';

	/**
	 * Primary Key
	 */
	var $_key = 'rad_result_image_id';

	/**
	 * Internal Name
	 */
	var $_internalName = 'RadResultImage';

	/**
	 * Handle instantiation
	 */
	function RadResultImage() {
		parent::ORDataObject();
		$link = Celini::link('UploadImageAjax', 'RadResult');
		$this->logger   =   LoggerManager::getLogger('modules.dept_rad.ordo.RadResultImage');
		$this->_module_dir        =   RadUtils::getModulePath();
		$this->_image_base_dir    =   $this->_module_dir . $this->_image_folder;
		$this->_setupTypeFolders();
	}

	private function _setupTypeFolders() {
        $list   =   array(
            Utils::getEnumKey(EnumerationConstant::PARACLINIC_TYPE, EnumerationConstant::PARACLINIC_XRAY)   => "x-ray/",
            Utils::getEnumKey(EnumerationConstant::PARACLINIC_TYPE, EnumerationConstant::PARACLINIC_ENDO)   => "endoscopy/",
            Utils::getEnumKey(EnumerationConstant::PARACLINIC_TYPE, EnumerationConstant::PARACLINIC_ULTRA)  => "ultrasound/"
        );
        $this->_type_folders    =   $list;
	}

	public function addImage($radTicketItemId, $fullImage, $thumnailImage, $fileType) {
        /*// Create image file names (Input: patientId, radType)
        $objRadItem     =   Celini::newORDO('RadTicketItem', $radTicketItemId);
        $objRadTicket   =   Celini::newORDO('RadTicket', $objRadItem->getRadTicketId());
        $radType        =   Utils::getEnumValue(EnumerationConstant::PARACLINIC_TYPE, $objRadTicket->getEnumRadType());

        // Create a folder for patient if it is not available
        $patientDir     =   $this->baseDir  . $objRadTicket->getPatientId() . "/";
        $this->logger->debug("Start creating radiology image folder for patient {patientId=" . $objRadTicket->getPatientId() . "}");
        if(!is_dir($patientDir)){
            mkdir($patientDir, 0777);
            chmod($patientDir, 0777);
        }
        $this->logger->debug("Finish creating radiology image folder for patient {patientId=" . $objRadTicket->getPatientId() ."}");
        // File locations
        $thumDir   =   $patientDir . $this->thumbnailFolder;
        $fullDir   =   $patientDir . $this->fullFolder;

        // Create forders if they do not exist
        $this->logger->debug("Start creating radiology full image subfolder for patient {patientId=}" . $objRadTicket->getPatientId());
	   if(!is_dir($thumDir)){
            mkdir($thumDir, 0777);
            chmod($thumDir, 0777);
        }
        $this->logger->debug("Finish creating radiology full image subfolder for patient {patientId=}" . $objRadTicket->getPatientId());
        $this->logger->debug("Start creating radiology thumbnail image subfolder for patient {patientId=}" . $objRadTicket->getPatientId());
	   if(!is_dir($fullDir)){
            mkdir($fullDir, 0777);
            chmod($fullDir, 0777);
        }
        $this->logger->debug("Finish creating radiology thumbnail image subfolder for patient {patientId=}" . $objRadTicket->getPatientId());
        // Create image file from image resource
        switch($fileType) {
        	case 'image/jpg':
        		$function =   'imagejpeg';
        		$ext      =   '.jpg';
                $break;
        	case 'image/jpeg':
        		$function =   'imagejpeg';
        		$ext      =   '.jpeg';
        		$break;
        	case 'image/gif':
        		$function =   'imagegif';
        		$ext      =   '.gif';
                $break;
            case 'image/png':
            default:
                $function =   'imagepng';
                $ext      =   '.png';
                $break;
        }
        $time =  date('YmdHis');
        $thumName   =   $radType . "_" . $time . "_thumnail" . $ext;
        $thumFile   =   $thumDir . $thumName;
        $this->logger->debug("Start creating thumbnail image {function='$function', fileName='$thumFile'}");
        $function($thumnailImage, $thumFile);
        $this->logger->debug("Finish creating thumbnail radiology image {function='$function', fileName='$thumDir'}");

        $fullName   =   $radType . "_" . $time . "_full" . $ext;
        $fullFile   =   $fullDir . $fullName;
        $this->logger->debug("Start creating full radiology image {function='$function', fileName='$fullFile', resource_size=". sizeof($fullImage). "}");
        $function($fullImage, $fullFile);
        $this->logger->debug("Finish creating full radiology image {function='$function', fileName='$fullFile'}");

        // Store data to database
        $data   =   array(
            'rad_item_id'   =>  $radTicketItemId,
            'full_url'      =>  $this->baseUrl . $objRadTicket->getPatientId() . "/" . "full/$fullName",
            'thumnail_url'  =>  $this->baseUrl . $objRadTicket->getPatientId() . "/" . "thumbnail/$thumName",
            'created'       =>  date('Y-m-d H:i:s')
        );
        $this->populateArray($data);
        $this->persist();

        return $this->get_id();*/
	}

	public function createImageDirectories($radTicketItemId) {
         // Create image file names (Input: patientId, radType)
        $objRadItem     =   Celini::newORDO('RadTicketItem', $radTicketItemId);
        $objRadTicket   =   Celini::newORDO('RadTicket', $objRadItem->getRadTicketId());
        $radType        =   Utils::getEnumValue(EnumerationConstant::PARACLINIC_TYPE, $objRadTicket->getEnumRadType());

        // Step 1: Check if image folder of module exist or not. If not, create one,
        $imageDir    =   APP_ROOT . $this->_image_base_dir;
        $this->logger->debug("Creating module image folder {dir='$imageDir'}");
        if(!is_dir($imageDir)){
            mkdir($imageDir, 0777);
            chmod($imageDir, 0777);
        }

        // Step 2: Check if image folder for radioloy type exist or not. If not, create one.
        $typeDir        =   $this->_image_base_dir . $this->_type_folders[$objRadTicket->getEnumRadType()];
        $typeDirRoot    =   APP_ROOT . $typeDir;
        $this->logger->debug("Creating radiology type image folder {dir='$typeDirRoot'}");
        if(!is_dir($typeDirRoot)){
            mkdir($typeDirRoot, 0777);
            chmod($typeDirRoot, 0777);
        }

        // Step 3: Check if image folder for current year exist or not. If not, create one.
        $curYear        =   date("Y");
        $yearDir        =   $typeDir . $curYear . "/";
        $yearDirRoot    =   APP_ROOT .    $yearDir;
        $this->logger->debug("Creating year image folder {dir='$yearDirRoot'}");
        if(!is_dir($yearDirRoot)){
            mkdir($yearDirRoot, 0777);
            chmod($yearDirRoot, 0777);
        }

    	// Step 4: Check if image folder for current month exist or not. If not, create one.
        $curMonth       =   date("m");
        $monthDir       =   $yearDir . $curMonth . "/";
        $monthDirRoot   =   APP_ROOT . $monthDir;
        $this->logger->debug("Creating month image folder {dir='$monthDirRoot'}");
        if(!is_dir($monthDirRoot)){
            mkdir($monthDirRoot, 0777);
            chmod($monthDirRoot, 0777);
        }

        // Step 5: Check if image folder for full and thumbnail images exist. If not, create them.
        $fullDir        =   $monthDir . $this->_full_folder;
        $fullDirRoot    =   APP_ROOT . $fullDir;
        $thumDir        =   $monthDir . $this->_thumnail_folder;
        $thumDirRoot    =   APP_ROOT . $thumDir;
        $this->logger->debug("Creating full image folder {dir='$fullDirRoot'}");
        if(!is_dir($fullDirRoot)){
            mkdir($fullDirRoot, 0777);
            chmod($fullDirRoot, 0777);
        }
        $this->logger->debug("Creating thumbnail image folder {dir='$thumDirRoot'}");
        if(!is_dir($thumDirRoot)){
            mkdir($thumDirRoot, 0777);
            chmod($thumDirRoot, 0777);
        }

        // Step 6: Create file name. Name format: [patient_id]_[rad_type]_[datetime]_[full/thumbnail]
        /// File name for full and thumbnail files
        $time       =   date('YmdHis');
        $thumName   =   $objRadTicket->getPatientId() . "_" . $radType . "_" . $time . "_thumbnail";
        $fullName   =   $objRadTicket->getPatientId() . "_" . $radType . "_" . $time . "_full";
        $result     =   array(
            'thumbnail' =>  $thumDir . $thumName,
            'full'      =>  $fullDir . $fullName
        );

        return $result;
	}

	public function setData($radTicketItemId, $fullUrl, $thumbnailUrl) {
        $data   =   array(
            'rad_item_id'   =>  $radTicketItemId,
            'full_url'      =>  $fullUrl,
            'thumnail_url'  =>  $thumbnailUrl,
            'created'       =>  date('Y-m-d H:i:s')
        );
        $this->populateArray($data);
	}

	public function getRadImagesByTicketItem($radTicketItemId) {
        $sql    =   array(
            'cols'  =>  "$this->_key id, full_url, thumnail_url",
            'from'  =>  "$this->_table",
            'where' =>  "rad_item_id='$radTicketItemId'"
        );
        $ds =   new Datasource_sql();
        $ds->setup($this->_db, $sql);

        return $ds->toArray();
	}

	public function deleteImage($radImageId) {
		$sql    =   "SELECT full_url, thumnail_url FROM $this->_table WHERE $this->_key  =  '$radImageId'";
		$res    =   $this->_execute($sql);
		if ($res && !$res->EOF) {
            $fullFile   =   APP_ROOT . $res->fields['full_url'];
            $thumbFile  =   APP_ROOT . $res->fields['thumnail_url'];
            unlink($fullFile);
            unlink($thumbFile);
		}

        $sql    =   "DELETE FROM $this->_table WHERE $this->_key    =   '$radImageId'";
        $this->_execute($sql);
	}

	public function getFullUrl() {
		return $this->full_url;
	}

	public function getThumbnailUrl() {
		return $this->thumnail_url;
	}
}
?>
